<?php
/**
 * @ClassName: Membertag
 * @Description: 用户标签
 * @author: gydtrade
 * @Date: 2024-09-10 22:17
 * @Version: V1.0.0
 */

namespace app\admin\controller;

use app\common\model;
use think\Controller;
use tpext\builder\traits\HasBuilder;

class Membertag extends Controller
{
    use HasBuilder;

    protected $dataModel;

    protected function initialize()
    {
        parent::initialize();

        $this->dataModel = new model\MemberTag();
        $this->pageTitle = '用户标签';
        $this->enableField = 'status';
        $this->pagesize = 10;

        $this->selectTextField = '{id}#{name}';
        $this->selectFields = 'id,name';
        $this->selectSearch = 'name';
    }

    /**
     * 构建搜索
     *
     * @return void
     */
    protected function buildSearch()
    {
        $search = $this->search;
        $search->text('name', '名称');
    }

    /**
     * 构建搜索条件
     * @return array
     */
    protected function filterWhere()
    {
        $searchData = request()->get();

        $where = [];
        if (!empty($searchData['name'])) {
            $where[] = ['name', 'like', '%' . $searchData['name'] . '%'];
        }
        return $where;
    }

    /**
     * 构建表格
     *
     * @return void
     */
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        $table->show('id', 'ID');
        $table->show('name', '名称');
        $table->show('description', '摘要');
        $table->text('sort', '排序')->autoPost('', true);
        $table->switchBtn('is_show', '显示')->autoPost('', true);
        $table->show('create_time', '添加时间');
        $table->show('update_time', '更新时间');

        $table->sortable('id, create_time');

        $table->getToolbar()
            ->btnAdd()
            ->btnRefresh();

        $table->getActionbar()
            ->btnEdit()
            ->btnView();
    }

    /**
     * 构建表单
     *
     * @param boolean $isEdit
     * @param array $data
     */
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;
        $form->text('name', '名称')->required();
        $form->textarea('description', '摘要');
        $form->number('sort', '排序')->required();
        $form->radio('is_show', '显示')->default(1)->required();

        if ($isEdit) {
            $form->show('create_time', '添加时间');
            $form->show('update_time', '修改时间');
        }
    }

    /**
     * 保存数据
     *
     * @param integer $id
     * @return void
     */
    private function save($id = 0)
    {
        $data = request()->post();
//        $data = request()->only([], 'post');

        $result = $this->validate($data, []);

        if (!$result) {
            $this->error($result);
        }

        if ($id) {
            // 编辑
            $data['update_time'] = date_now();
        } else {
            // 新增
            $data['create_time'] = date_now();
            $data['update_time'] = date_now();
        }

        return $this->doSave($data, $id);
    }

}